﻿using System;
using System.ComponentModel.Composition;
using System.Net;
using System.Web.Mvc;
using ChiDao.Business.Service;
using ChiDao.Site.Models;
using Ext.Net;
using Ext.Net.MVC;
using ChiDao.Business.Models.Security;
using System.Collections.Generic;
using ChiDao.Component.Utils;

namespace ChiDao.Site.Web.Controllers
{
    [DirectController]
    [Export]
    public class MainController : BaseController
    {
        //[Import]
        //public IBaklogTaskService BaklogTaskSiteContract { get; set; }

        [Import]
        public IMenuInfoService MenuContract { get; set; }

        public string ContainerId = "";

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult MainHome()
        {
            return View();
        }

        [OutputCache(Duration = 3600)]
        public ActionResult GetNavNodes(string node)
        {
            if (node == "Root")
            {
                //return this.Content(NavModel.GetNavNodes().ToJson());   //修改这个，从数据库获取用户的菜单

                return this.Content(this.GetMenuTree().ToJson());
            }

            return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
        }

        /// <summary>
        /// 获取菜单树
        /// </summary>
        /// <returns></returns>
        private NodeCollection GetMenuTree()
        {
            var nodes = new NodeCollection();
            List<MenuInfo> menus = MenuContract.GetMenusByUserName(User.Identity.Name);
            foreach (MenuInfo menu in menus)
            {
                //非节点，且PID=null（一级菜单）
                if (!menu.IsLeaf && menu.PID == null)
                {
                    Node pNode = new Node();
                    pNode.NodeID = menu.ID.ToString();

                    pNode.Text = menu.MenuName;
                    pNode.Leaf = menu.IsLeaf;
                    //pNode.IconCls = string.Empty;

                    //如果没有子节点，则不加入菜单
                    bool isHasChildren = menus.FindAll(m => m.PID == menu.ID).Count > 0;
                    if (isHasChildren)
                    {
                        nodes.Add(pNode);
                        CreateChildrenNode(menus, pNode);  //创建子节点
                    }
                }
            }
            return nodes;
        }

        /// <summary>
        /// 创建子节点（递归）
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="pNode"></param>
        private void CreateChildrenNode(List<MenuInfo> menus, Node pNode)
        {
            Node node = null;

            Guid pid = pNode.NodeID.ToGuid();

            var cMenus = menus.FindAll(m => m.PID == pid);
            foreach (MenuInfo cMenu in cMenus)
            {
                node = new Node();
                node.NodeID = cMenu.ID.ToString();
                node.Text = cMenu.MenuName;
                string url = string.Concat(NavModel.ApplicationRoot, "/", string.Format("{0}/{1}", cMenu.ControllerName, cMenu.ActionName), "/");
                node.Href = url;
                node.Leaf = cMenu.IsLeaf;
                pNode.Children.Add(node);

                CreateChildrenNode(menus, node);  //递归子节点
            }
        }

        [DirectMethod]
        [OutputCache(Duration = 86400, VaryByParam = "theme")]
        public DirectResult GetThemeUrl(string theme)
        {
            Theme temp = (Theme)Enum.Parse(typeof(Theme), theme);

            this.Session["Ext.Net.Theme"] = temp;

            return this.Direct(temp == Ext.Net.Theme.Default ? "Default" : MvcResourceManager.GetThemeUrl(temp));
        }

        [DirectMethod]
        [OutputCache(Duration = 86400, VaryByParam = "name")]
        public DirectResult GetHashCode(string name)
        {
            return this.Direct(Math.Abs(name.ToLower().GetHashCode()));
        }

        [DirectMethod]
        public DirectResult ChangeScriptMode(bool debug)
        {
            if (debug)
            {
                this.Session["Ext.Net.ScriptMode"] = Ext.Net.ScriptMode.Debug;
                this.Session["Ext.Net.SourceFormatting"] = true;
            }
            else
            {
                this.Session["Ext.Net.ScriptMode"] = Ext.Net.ScriptMode.Release;
                this.Session["Ext.Net.SourceFormatting"] = false;
            }

            Response.Redirect("");

            return this.Direct();
        }

        public ActionResult PorletBaklogTask()
        {
            return this.PartialView("PorletBaklogTask");
        }

        public ActionResult MainNavigation()
        {
            return this.PartialView("MainNavigation");
        }

        public ActionResult MainPortals()
        {
            return this.PartialView("MainPortals");
        }

        public RedirectToRouteResult QueryHolidayDocument()
        {
            return this.RedirectToAction("QueryRequestHolidayDocument", "HolidayDocument");
        }

        public ActionResult AddTab(string viewName, string containerId = "mainTabPnl")
        {
            var result = new Ext.Net.MVC.PartialViewResult
            {
                ViewName = viewName,
                ContainerId = containerId,
                RenderMode = RenderMode.AddTo
            };

            this.GetCmp<TabPanel>("mainTabPnl").SetLastTabAsActive();

            return result;
        }
    }
}